package net.yxsoft.service.formdisigner;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.enumclass.EditorTypesEnumCls;
import net.yxsoft.enumclass.WhetherEnumCls;
import net.yxsoft.kit.CustomDb;
import net.yxsoft.model.formdesigner.Form;
import net.yxsoft.model.formdesigner.FormField;
import net.yxsoft.model.infrastructure.TsDatamodelProperties;
import net.yxsoft.resource.SqlRes;
import net.yxsoft.resource.TableRes;
import rapid.core.TResult;
import rapid.jfinal.BaseService;
import rapid.jfinal.ParamKeyMap;
import rapid.util.StrKit;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author zhaohaibo
 */
public class FormFieldService extends BaseService {

  /**
  * @MethodName: find
  * @Description:
  * @param: params
  * @return * @return java.util.List<net.yxsoft.model.formdesigner.FormField>
  * @throws
  * @date 2023/8/31 14:03
  * @author wj
  */
  public List<FormField> find(ParamKeyMap params) {
    return FormField.dao.find(Db.getSqlPara(SqlRes.FORM_DESIGNER + "findFormFields", params.toKv()));
  }
  /**
  * @MethodName: findBase
  * @Description:
  * @param: formId
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 14:03
  * @author wj
  */
  public List<Record> findBase(String formId) {
    return Db.find(Db.getSqlPara(SqlRes.FORM_DESIGNER + "findFormBaseFields", Kv.by("form_id", formId)));
  }
  
  /**
  * @MethodName: findImageUploader
  * @Description:
  * @param: formId
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 14:03
  * @author wj
  */
  public List<Record> findImageUploader(String formId) {
    return Db.find(Db.getSqlPara(SqlRes.FORM_DESIGNER + "findFormImageUploaderFields", Kv.by("form_id", formId)));
  }

  /**
  * @MethodName: findWithRecord
  * @Description: 
  * @param: params
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws 
  * @date 2023/8/31 14:03
  * @author wj 
  */
  public List<Record> findWithRecord(ParamKeyMap params) {
    return Db.find(Db.getSqlPara(SqlRes.FORM_DESIGNER + "findFormFields", params.toKv()));
  }
  
  /**
  * @MethodName: checkDulpicate
  * @Description: 检查是否重复
  * @param: obj
  * @return * @return rapid.core.TResult
  * @throws 
  * @date 2023/8/31 14:03
  * @author wj 
  */
  public TResult checkDulpicate(FormField obj) {
    FormField temp;
    FormField temp1;

    String id=obj.getId();
    String formId = obj.getFormId();
    String title = obj.getTitle();
    String name = obj.getName();
    BigDecimal sort = obj.getSort();
    String type = obj.getType();


    if(id != null) {
      temp = FormField.dao.findFirst("select title, name, sort from " + TableRes.FORM_FIELD +
                                       " where id <> ? and form_id = ? and (title = ? or name = ? or (sort <> 0 and sort = ?))", id, formId, title, name, sort);

      temp1 = FormField.dao.findFirst("select title, name, sort from " + TableRes.FORM_FIELD +
                                       " where id <> ? and form_id = ? and type='webuploader' ", id, formId);

    } else {
      temp = FormField.dao.findFirst("select title, name, sort from " + TableRes.FORM_FIELD +
                                       " where form_id = ? and (title = ? or name = ? or (sort <> 0 and sort = ?))", formId, title, name, sort);


      temp1 = FormField.dao.findFirst("select title, name, sort from " + TableRes.FORM_FIELD +
                                        " where  form_id = ? and type='webuploader' ", formId);

    }



    if(temp != null) {
      if(temp.getTitle().equals(title)) {
        return fail().msg("名称有重复。");
      }

      if(temp.getName().equals(name)) {
        return fail().msg("映射字段名有重复。");
      }

      if(temp.getSort().equals(sort)) {
        return fail().msg("位置有重复。");
      }
    }

    return success();
  }

  
  /**
  * @MethodName: add
  * @Description: 
  * @param: obj
  * @return * @return rapid.core.TResult
  * @throws 
  * @date 2023/8/31 14:04
  * @author wj 
  */
  public TResult add(FormField obj) {
    if(obj == null) {
      return fail();
    }

    if(StrKit.notBlank(obj.getCodeResource()) && obj.getCodeResource().indexOf("|") > 0) {
      String[] codes = obj.getCodeResource().split("\\|"); //切割 codename|customid|codetype
      if(codes.length == 3 && com.jfinal.kit.StrKit.notBlank(codes[0]) && com.jfinal.kit.StrKit.notBlank(codes[1]) && com.jfinal.kit.StrKit.notBlank(codes[2])) {
        obj.setCodeName(codes[0]);
        obj.setCodeType(codes[2]);
        obj.setCodeLeaf(com.jfinal.kit.StrKit.notBlank(obj.getCodeLeaf()) ? obj.getCodeLeaf() : "2");
      }
    } else {
      obj.setCodeName(null);
      obj.setCodeType(null);

      if(StrKit.notBlank(obj.getCodeLeaf())){
        obj.setCodeLeaf(obj.getCodeLeaf());
      }else
        obj.setCodeLeaf(null);
    }

    if(StrKit.notBlank(obj.getName()) && obj.getName().indexOf("|") > 0) {
      obj.setField(obj.getName().split("\\|")[0]);
    }

    if(WhetherEnumCls.YES.getValue().equals(obj.getIsSum()) &&
      (!EditorTypesEnumCls.number.getValue().equalsIgnoreCase(obj.getType()) && !EditorTypesEnumCls.digitbox.getValue().equalsIgnoreCase(obj.getType()))){

      return fail().msg("汇总项必须为数值型");
    }

    obj.setState(1);

    TResult rs = checkDulpicate(obj);

    if(rs.isFail()) {
      return rs;
    }
    if(StrKit.isBlank(obj.getIsEditor())){
      obj.setIsEditor("1");
    }


    if(obj.getSort() == null) {
      obj.setSort(BigDecimal.ZERO);
    }

    TResult tResult =obj.save() ? success() : fail();
    if(tResult.isSuccess()){
      Form form=Form.dao.findById(obj.getFormId());
      if(form!=null && StrKit.notBlank(form.getModel())){
        TsDatamodelProperties tsDatamodelProperties=TsDatamodelProperties.dao.findFirst("select t.* from ts_datamodel_properties t left join ts_party t1 on t.model_id=t1.conflict_id where t1.name=? and t.attrib_name=?",form.getModel(),obj.getField());
        if(tsDatamodelProperties!=null){
          CustomDb.updateWithExceptionHandling("update ts_datamodel_properties set attrib_descn=null,state=0 where model_id=? and attrib_descn=?",tsDatamodelProperties.getModelId(),obj.getTitle());

          tsDatamodelProperties.setAttribDescn(obj.getTitle());
          tsDatamodelProperties.setCodeLeaf(obj.getCodeLeaf());
          tsDatamodelProperties.setCodeName(obj.getCodeName());
          tsDatamodelProperties.setCodeType(obj.getCodeType());
          tsDatamodelProperties.setCodeCustomid(obj.getCodeType());
          tsDatamodelProperties.update();
        }

      }
    }

    return tResult;
  }

  public TResult update(FormField obj) {
    if(obj == null) {
      return fail();
    }

    TResult rs = checkDulpicate(obj);

    if(rs.isFail()) {
      return rs;
    }

    if(WhetherEnumCls.YES.getValue().equals(obj.getIsSum()) &&
        (!EditorTypesEnumCls.number.getValue().equalsIgnoreCase(obj.getType()) && !EditorTypesEnumCls.digitbox.getValue().equalsIgnoreCase(obj.getType()))){

      return fail().msg("汇总项必须为数值型");
    }

    FormField old = FormField.dao.findById(obj.getId());
    if(old == null) {
      return fail().msg("记录不存在或已被删除。");
    }

    if(StrKit.notBlank(obj.getCodeResource()) && obj.getCodeResource().indexOf("|") > 0) {
      String[] codes = obj.getCodeResource().split("\\|"); //切割 codename|customid|codetype
      if(codes.length == 3 && com.jfinal.kit.StrKit.notBlank(codes[0]) && com.jfinal.kit.StrKit.notBlank(codes[1]) && com.jfinal.kit.StrKit.notBlank(codes[2])) {
        old.setCodeName(codes[0]);
        old.setCodeResource(obj.getCodeResource());
        old.setCodeType(codes[2]);
        old.setCodeLeaf(com.jfinal.kit.StrKit.notBlank(obj.getCodeLeaf()) ? obj.getCodeLeaf() : "2");
      }
    } else {
      old.setCodeName(null);
      old.setCodeResource(null);
      obj.setCodeType(null);
      if(StrKit.notBlank(obj.getCodeLeaf())){
        old.setCodeLeaf(obj.getCodeLeaf());
      }else
        old.setCodeLeaf(null);
    }

    if(StrKit.notBlank(obj.getName()) && obj.getName().indexOf("|") > 0) {
      old.setField(obj.getName().split("\\|")[0]);
    }

    old.setSort(obj.getSort() == null ? BigDecimal.ZERO : obj.getSort());
    old.setTitle(obj.getTitle());
    old.setName(obj.getName());
    old.setType(obj.getType());
    old.setFileSize(obj.getFileSize());
    old.setFileMaxSize(obj.getFileMaxSize());
    old.setRequired(obj.getRequired());
    old.setDataSourceId(obj.getDataSourceId());
    old.setNote(obj.getNote());
    old.setNumberMaxValue(obj.getNumberMaxValue());
    old.setNumberMinValue(obj.getNumberMinValue());
    old.setGirdFieldWidth(obj.getGirdFieldWidth());
    old.setStringMaxLength(obj.getStringMaxLength());
    old.setControllerId(obj.getControllerId());
    old.setGridFieldVisible(obj.getGridFieldVisible());
    old.setIsSearch(obj.getIsSearch());
    old.setIsExport(obj.getIsExport());
    old.setIsSum(obj.getIsSum());
    old.setIsTypeSum(obj.getIsTypeSum());
    old.setColSpan(obj.getColSpan());
    old.setGridShowName(obj.getGridShowName());
    old.setDefaultValue(obj.getDefaultValue());
    old.setCustomDataUrl(obj.getCustomDataUrl());
    old.setCustomDataOption(obj.getCustomDataOption());
    old.setDataOnly(obj.getDataOnly());
    old.setIsCascade(obj.getIsCascade());
    old.setCascadeField(obj.getCascadeField());
    old.setValidatorType(obj.getValidatorType());
    old.setIsEditor(obj.getIsEditor());

    TResult tResult= old.update() ? success() : fail();
    if(tResult.isSuccess()){
      Form form=Form.dao.findById(obj.getFormId());
      if(form!=null && StrKit.notBlank(form.getModel())){
        TsDatamodelProperties tsDatamodelProperties=TsDatamodelProperties.dao.findFirst("select t.* from ts_datamodel_properties t left join ts_party t1 on t.model_id=t1.conflict_id where t1.name=? and t.attrib_name=?",form.getModel(),old.getField());
        if(tsDatamodelProperties!=null){
          CustomDb.updateWithExceptionHandling("update ts_datamodel_properties set attrib_descn=null,state=0 where model_id=? and attrib_descn=?",tsDatamodelProperties.getModelId(),old.getTitle());

          tsDatamodelProperties.setAttribDescn(old.getTitle());
          tsDatamodelProperties.setState(0);
          tsDatamodelProperties.setCodeLeaf(old.getCodeLeaf());
          tsDatamodelProperties.setCodeName(old.getCodeName());
          tsDatamodelProperties.setCodeType(old.getCodeType());
          tsDatamodelProperties.setCodeCustomid(old.getCodeType());
          tsDatamodelProperties.update();
        }

      }
    }
    return tResult;
  }
  
  /**
  * @MethodName: findCascadeFileds
  * @Description: 查询当前表单中未被绑定的级联单选字段
  * @param: formid
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 14:04
  * @author wj
  */
  public List<Record> findCascadeFileds(String formid){



    List<Record> recordList = Db.find("select field cascade_field, concat(field,'|',title) ftitle \n" +
        "  from fn_form_field ff\n" +
        "where form_id = ? \n" +
        " and type = 'picker' and state = '1' and code_leaf in ('3', '4')", formid);
    return recordList;
  }

  /**
  * @MethodName: toggleDisabled
  * @Description: 
  * @param: id
 * @param: state
  * @return * @return rapid.core.TResult
  * @throws 
  * @date 2023/8/31 14:28
  * @author wj 
  */
  public TResult toggleDisabled(String id, String state) {
    if(StrKit.isEmpty(id)) {
      return success();
    }

    CustomDb.updateWithExceptionHandling("update " + TableRes.FORM_FIELD + " set state = ? where id = ?", state, id);

    return success();
  }
}
